﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetComponentsDx.Forms;
using DevExpress.XtraGrid.Columns;
using ProgNetComponentsDx.Options;

namespace BuildHelper.Setup.Srodowiska
{
    public partial class FormSrodowiska : MyBaseSqlCeGridForm
    {
        public static FormSrodowiska Instance
        {
            get;
            private set;
        }
        public FormSrodowiska()
        {
            InitializeComponent();
            Instance = this;
            this.rep_colOtworz.Buttons[0].Image = this.commonImageCollectionFull1.Images[40].ResizeImage(18, 18);
            this.rep_colSprawdz.Buttons[0].Image = this.commonImageCollectionFull1.Images[86].ResizeImage(18, 18);
        }

        protected override void FinishEdit()
        {
            base.FinishEdit();
        }
        protected override bool Save()
        {
            DataRow[] rows = srodowiskaDataSet.STP_SRODOWISKA.Select("STP_SR_WLASNE = 1", null, DataViewRowState.ModifiedCurrent | DataViewRowState.Added);
            if (rows != null)
                foreach (DataRow r in rows)
                    r["STP_SR_DATA_AKTUALIZACJI"] = DateTime.Now;

            return base.Save();
        }
        int progress = 0;
        int max;
        object lockProgress = new object();
        object lockDataSet = new object();
        
        private void bbiSzukaj_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SearchForEnvs();
        }
       
        private void SearchForEnvs()
        {
            if (backgroundControl.IsRunning)
            {
                this.ShowDxInfoDialog("Operacja w toku.");
                return;
            }
            backgroundControl.ClearActions();
            backgroundControl.AddAction(new Action(UpdateEnvs));
            backgroundControl.Start();
        }
        private void UpdateEnvs()
        {
            Tools.UpdateEnvs(this.backgroundControl, this.srodowiskaDataSet);
        }

        void backgroundControl_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (srodowiskaDataSet.HasChanges())
                changeDetectorProvider1.SetModified();
        }

        private void bbiSprawdzWszystkie_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!backgroundControl.IsRunning)
            {
                List<DataRow> list = new List<DataRow>();
                List<DataRow> rows = new List<DataRow>();
                DataRow row;
                for (int i = 0; i < gvMain.RowCount; i++)
                {
                    row = gvMain.GetDataRow(i);
                    if (row != null)
                        rows.Add(row);
                }
                progress = 0;
                max = rows.Count;
                backgroundControl.SupportCancelation = true;
                backgroundControl.ProgressType = ProgressType.Percentage;
                backgroundControl.MaxProgress = max;
                backgroundControl.LabelText = "Sprawdzanie środowisk";
                backgroundControl.ClearActions();
                int minCount = 0;
                int minProc = 10;
                minCount = max / minProc;
                foreach (DataRow r in rows)
                {
                    list.Add(r);
                    if (list.Count >= minCount)
                    {
                        backgroundControl.AddAction(new Action<List<DataRow>>(CheckRespond), new object[] { list });
                        list = new List<DataRow>();
                    }
                }
                if (list.Count > 0)
                    backgroundControl.AddAction(new Action<List<DataRow>>(CheckRespond), new object[] { list });
            }
            backgroundControl.Start();
        }
        
        private void rep_colOtworz_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenSelectedUrl();
        }

        private void rep_colSprawdz_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (modeProvider1.CurrentMode != ProgNetComponentsDx.Enums.FormMode.Read)
            {
                if (!backgroundControl.IsRunning)
                {
                    DataRow r = gvMain.GetFocusedDataRow();
                    if (r.CanRead())
                    {
                        string env = r["STP_SR_NAZWA"].AsString();

                        backgroundControl.SupportCancelation = true;
                        backgroundControl.ProgressType = ProgressType.Merque;
                        backgroundControl.LabelText = "Uaktualianie środowiska " + env;
                        backgroundControl.ClearActions();
                        backgroundControl.AddAction(new Action<DataRow>(CheckRespond), r);
                    }
                }
                backgroundControl.Start();
            }
        }

        private void CheckSelected()
        {
            DataRow r = gvMain.GetFocusedDataRow();
            if (r != null)
            {
                if (!backgroundControl.IsRunning)
                {
                    List<DataRow> list = new List<DataRow>();
                    progress = 0;
                    max = 1;
                    backgroundControl.SupportCancelation = false;
                    backgroundControl.ProgressType = ProgressType.Merque;
                    backgroundControl.LabelText = "Sprawdzanie środowiska " + r["STP_SR_NAZWA"];
                    backgroundControl.ClearActions();
                    list.Add(r);
                    backgroundControl.AddAction(new Action<List<DataRow>>(CheckRespond), new object[] { list });
                }
                backgroundControl.Start();
            }
        }
        private void CheckRespond(List<DataRow> rows)
        {
            foreach (DataRow r in rows)
            {
                if (backgroundControl.IsCanceling)
                    return;
                CheckRespond(r);
            }
        }

        private void CheckRespond(DataRow r)
        {
            if (backgroundControl.IsCanceling)
                return;
            bool respond = Tools.CheckUrl(r["STP_SR_URL"].AsString());
            lock (lockDataSet)
            {
                UpdateRow(r, respond);
            }
            if (backgroundControl.ProgressType == ProgressType.Percentage)
            {
                lock (lockProgress)
                {
                    backgroundControl.Progress = progress++;
                }
                backgroundControl.Label2Text = (progress + "/" + max);
            }
        }

        private void UpdateRow(DataRow r, bool respond)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<DataRow, bool>(UpdateRow), r, respond);
                return;
            }
            if(r.SetColVal("STP_SR_DZIALA", respond))
                changeDetectorProvider1.SetModified();
        }

        private void bbiOpen_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenSelectedUrl();
        }


        public void MergeRow(Tools.EnvData e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<Tools.EnvData>(MergeRow), e);
                return;
            }
           
            DataRow r = this.srodowiskaDataSet.STP_SRODOWISKA.SelectFirstRow("STP_SR_NAZWA = " + e.EnvName.EscapeSql());
            bool modified = true;
            
            if (r == null)
            {
                if (modeProvider1.CurrentMode != ProgNetComponentsDx.Enums.FormMode.Edit)
                    modeProvider1.CurrentMode = ProgNetComponentsDx.Enums.FormMode.Edit;
                
                r = srodowiskaDataSet.STP_SRODOWISKA.NewRow();
                r["STP_SR_NAZWA"] = e.EnvName;
                srodowiskaDataSet.STP_SRODOWISKA.Rows.Add(r);
                modified = false;
            }

            modified |= r.SetColVal("STP_SR_DZIALA", e.Dziala);
             modified |= r.SetColVal("STP_SR_HOST", e.Host);
            if (e.Port.IsNotNull())
                 modified |= r.SetColVal("STP_SR_PORT", e.Port);
            else
                modified |= r.SetColVal("STP_SR_PORT", DBNull.Value);
             modified |= r.SetColVal("STP_SR_WLASNE", false);
             modified |= r.SetColVal("STP_SR_URL", e.Url);
             modified |= r.SetColVal("STP_SR_WERSJA", e.Wersja);
             modified |= r.SetColVal("STP_SR_DATA_AKTUALIZACJI", DateTime.Now);
             if (r.RowState != DataRowState.Added && modified)
             {
                 if (modeProvider1.CurrentMode != ProgNetComponentsDx.Enums.FormMode.Edit)
                     modeProvider1.CurrentMode = ProgNetComponentsDx.Enums.FormMode.Edit;
                 changeDetectorProvider1.SetModified();
             }
        }

        private void OpenSelectedUrl()
        {
            DataRow r = gvMain.GetFocusedDataRow();
            if (r != null)
            {
                string url = r["STP_SR_URL"].AsString();
                Tools.OpenUrl(url);
            }
        }
        private void modeProvider1_CustomGetModes(object sender, ProgNetComponentsDx.Mode.CustomModeSettingsEventArgs e)
        {
            if (sender == colSTP_SR_FAV)
                return;

            if (sender is GridColumn)
            {
                if (e.Row != null && !e.Row["STP_SR_WLASNE"].AsBool())
                {
                    e.IsReadOnly = true;
                }
            }
        }
        protected override void OnClosed(EventArgs e)
        {
            Instance = null;
            base.OnClosed(e);
            backgroundControl.SupportCancelation = true;
            backgroundControl.Cancel();
        }
       
        public void EnvsModified()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(EnvsModified));
                return;
            }
            if (modeProvider1.CurrentMode != ProgNetComponentsDx.Enums.FormMode.Read)
                this.ShowDxInfoDialog("Środowiska zostały zmienione i muszą być przeładowane.");
            this.GetRecords();
        }
    }
}
